package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.consts.RabbitConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.payment.properties.AlipayProperties;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.rabbit.component.RabbitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author:lyd
 **/
@RestController
@RequestMapping("/api/payment")
@Slf4j
public class PayController {

    @Autowired
    AlipayService alipayService;
    @Autowired
    AlipayProperties alipayProperties;
    @Autowired
    RabbitService rabbitService;

    @GetMapping("/alipay/submit/{orderId}")
    public String submit(@PathVariable("orderId") Long orderId) throws AlipayApiException {
        // 调用支付宝接口,返回支付宝二维码收银页面
        String html = alipayService.getPayPage(orderId);
        return html;
    }

    /**
     * 支付宝支付成功后的异步回调
     *  jslfom5361@sandbox.com
     * @return
     */
    @PostMapping("/alipay/notify/success")
    public String notifySuccess(@RequestParam Map<String, String> map) throws AlipayApiException {
        log.info("支付成功：{}", JsonUtil.objToJsonStr(map));
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(map, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        if (signVerified) {
            //关单
            rabbitService.sendMsg(RabbitConst.EXCHANGE_ORDER_EVENT,RabbitConst.ROUTING_KEY_ORDER_PAYED,map);
            return "success";
        }else {
            log.error("验签失败");
            return "error";
        }

    }
}
